import 'dart:async';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/providers/spring_activity_provider.dart';
import '../../core/providers/navigation_provider.dart';
import '../../core/models/spring_activity_model.dart';

class ResidenceDisplayScreen extends ConsumerStatefulWidget {
  const ResidenceDisplayScreen({super.key});

  @override
  ConsumerState<ResidenceDisplayScreen> createState() =>
      _ResidenceDisplayScreenState();
}

class _ResidenceDisplayScreenState
    extends ConsumerState<ResidenceDisplayScreen> {
  ScrollController? _firstRowController;
  ScrollController? _secondRowController;

  Timer? _autoScrollTimer;

  List<Map<String, String>> _getAllRegistrationData() {
    final activityNotifier = ref.watch(springActivityProvider.notifier);
    final allRegistrations = <Map<String, String>>[];

    final activities = activityNotifier.getAllActivities();

    for (final activity in activities) {
      final registrations = activityNotifier.getActivityRegistrations(
        activity.activityId,
      );
      for (final registration in registrations) {
        allRegistrations.add({
          'userName': registration.userName,
          'userAvatar': registration.userAvatar,
          'activityTitle': activity.title,
          'activityId': activity.activityId,
          'message':
              '${registration.userName} just signed up for the ${activity.title}',
        });
      }
    }

    return allRegistrations;
  }

  @override
  void initState() {
    super.initState();
    _firstRowController = ScrollController();
    _secondRowController = ScrollController();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startAutoScroll();
    });
  }

  @override
  void dispose() {
    _autoScrollTimer?.cancel();
    _firstRowController?.dispose();
    _secondRowController?.dispose();
    super.dispose();
  }

  void _startAutoScroll() {
    _autoScrollTimer = Timer.periodic(const Duration(milliseconds: 50), (
      timer,
    ) {
      if (_firstRowController?.hasClients == true &&
          _secondRowController?.hasClients == true) {
        final firstController = _firstRowController!;
        final firstMaxScroll = firstController.position.maxScrollExtent;
        final firstCurrentScroll = firstController.offset;
        final firstNextScroll = firstCurrentScroll + 1.0;

        if (firstNextScroll >= firstMaxScroll) {
          firstController.jumpTo(0);
        } else {
          firstController.jumpTo(firstNextScroll);
        }

        final secondController = _secondRowController!;
        final secondMaxScroll = secondController.position.maxScrollExtent;
        final secondCurrentScroll = secondController.offset;
        final secondNextScroll = secondCurrentScroll - 1.0;

        if (secondNextScroll <= 0) {
          secondController.jumpTo(secondMaxScroll);
        } else {
          secondController.jumpTo(secondNextScroll);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: [
          _renderTopBar(),
          _renderScrollableContent().expanded(),
        ].toColumn().safeArea(bottom: false),
      ),
    );
  }

  Widget _renderTopBar() {
    return [
          Text('Spring Outing')
              .fontSize(24.sp)
              .bold()
              .textColor(Colors.black)
              .fontFamily('PoetsenOne'),
          Container(
            width: 32.w,
            height: 32.h,
            decoration: BoxDecoration(
              color: Colors.black,
              shape: BoxShape.circle,
            ),
            child:
                Icon(
                  AliIcons.iconNotify,
                ).iconSize(16.sp).iconColor(Colors.white).center(),
          ).inkWell(
            onTap: () {
              ref.read(navigationProvider.notifier).switchToMessageTab();
            },
          ),
        ]
        .toRow(mainAxisAlignment: MainAxisAlignment.spaceBetween)
        .padding(horizontal: 16.w, vertical: 12.h);
  }

  Widget _renderScrollableContent() {
    return [
      SizedBox(height: 20.h),
      _renderAiImageButton(),
      SizedBox(height: 20.h),
      _renderFirstRowCards(),
      SizedBox(height: 12.h),
      _renderSecondRowCards(),
      SizedBox(height: 20.h),
      _renderActivitySection(),
      SizedBox(height: 100.h),
    ].toColumn().scrollable();
  }

  Widget _renderAiImageButton() {
    return Stack(
          clipBehavior: Clip.none,
          children: [
            AspectRatio(
              aspectRatio: 374 / 150,
              child: Image.asset(
                'assets/resources/ai_bg.png',
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    decoration: BoxDecoration(
                      color: const Color(0xFF2AB061),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child:
                        Icon(
                          Icons.image,
                          size: 50.sp,
                          color: Colors.white,
                        ).center(),
                  );
                },
              ),
            ).parent(
              ({required Widget child}) => Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.r),
                ),
                clipBehavior: Clip.hardEdge,
                child: child,
              ),
            ),
            Positioned(
              left: 0.w,
              top: -30.h,
              child: Image.asset(
                'assets/resources/kid.png',
                width: 141.w,
                height: 190.h,
                fit: BoxFit.contain,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    width: 60.w,
                    height: 60.h,
                    decoration: BoxDecoration(
                      color: Colors.white.withValues(alpha: 0.8),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child:
                        Icon(
                          Icons.child_care,
                          size: 30.sp,
                          color: const Color(0xFF2AB061),
                        ).center(),
                  );
                },
              ),
            ),
          ],
        )
        .inkWell(
          onTap: () {
            GoRouter.of(context).push('/ai-chat');
          },
        )
        .padding(horizontal: 16.w);
  }

  Widget _renderFirstRowCards() {
    final allRegistrations = _getAllRegistrationData();

    if (allRegistrations.isEmpty) {
      return SizedBox(height: 48.h);
    }

    return SizedBox(
      height: 48.h,
      child: ListView.builder(
        controller: _firstRowController,
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        itemCount: allRegistrations.length * 10,
        itemBuilder: (context, index) {
          final registrationData =
              allRegistrations[index % allRegistrations.length];
          return _buildActivityRegistrationCard(registrationData);
        },
      ),
    );
  }

  Widget _renderSecondRowCards() {
    final allRegistrations = _getAllRegistrationData();

    if (allRegistrations.isEmpty) {
      return SizedBox(height: 48.h);
    }

    return SizedBox(
      height: 48.h,
      child: ListView.builder(
        controller: _secondRowController,
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.only(left: 121.w, right: 16.w),
        itemCount: allRegistrations.length * 10,
        itemBuilder: (context, index) {
          final reversedIndex =
              (allRegistrations.length - 1 - index) % allRegistrations.length;
          final registrationData = allRegistrations[reversedIndex];
          return _buildActivityRegistrationCard(registrationData);
        },
      ),
    );
  }

  Widget _buildActivityRegistrationCard(Map<String, String> registrationData) {
    return Container(
      width: 198.w,
      margin: EdgeInsets.only(right: 12.w),
      child: AspectRatio(
        aspectRatio: 198 / 48,
        child: Container(
          decoration: BoxDecoration(
            image: const DecorationImage(
              image: AssetImage('assets/resources/home_card_bg.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: [
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: AssetImage(registrationData['userAvatar']!),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SizedBox(width: 8.w),
            Expanded(
              child: Text(
                '${registrationData['userName']} just signed up for the ${registrationData['activityTitle']}',
                style: TextStyle(
                  fontSize: 10.sp,
                  color: Colors.black,
                  fontFamily: 'PoetsenOne',
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ].toRow().padding(horizontal: 8.w, vertical: 4.h),
        ),
      ),
    ).inkWell(
      onTap: () {
        final activityId = registrationData['activityId'];
        if (activityId != null && activityId.isNotEmpty) {
          GoRouter.of(context).push('/activity-detail/$activityId');
        }
      },
    );
  }

  Widget _renderActivitySection() {
    final activityNotifier = ref.watch(springActivityProvider.notifier);
    final activities = activityNotifier.getAllActivities();

    return Stack(
      clipBehavior: Clip.none,
      children: [
        Column(
          children: [
            SizedBox(height: 52.h),
            if (activities.isNotEmpty)
              _renderActivityItem(
                activities[0],
                'assets/resources/activity_1.png',
                374 / 201,
              ),
            if (activities.length > 1)
              _renderActivityItem(
                activities[1],
                'assets/resources/activity_2.png',
                374 / 177,
              ),
            if (activities.length > 2)
              _renderActivityItem(
                activities[2],
                'assets/resources/activity_3.png',
                374 / 177,
              ),
            if (activities.length > 3)
              _renderActivityItem(
                activities[3],
                'assets/resources/activity_4.png',
                374 / 177,
              ),
            SizedBox(height: 20.h),
          ],
        ),
        Positioned(
          top: 20.h,
          left: 0,
          right: 0,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              AspectRatio(
                aspectRatio: 354 / 52,
                child: Image.asset(
                  'assets/resources/activity_top.png',
                  fit: BoxFit.fill,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      decoration: BoxDecoration(
                        color: const Color(0xFF2AB061),
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child:
                          Text('Activities')
                              .fontSize(18.sp)
                              .bold()
                              .textColor(Colors.white)
                              .center(),
                    );
                  },
                ),
              ),
              Positioned(
                left: -30.w,
                top: -36.h,
                child: SizedBox(
                  width: 91.w,
                  height: 91.h,
                  child: Image.asset(
                    'assets/resources/activity_notify.png',
                    width: 91.w,
                    height: 91.h,
                    fit: BoxFit.contain,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        width: 50.w,
                        height: 50.h,
                        decoration: BoxDecoration(
                          color: const Color(0xFFFDDB31),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child:
                            Icon(
                              Icons.notifications,
                              size: 20.sp,
                              color: Colors.black,
                            ).center(),
                      );
                    },
                  ),
                ),
              ),
            ],
          ).padding(horizontal: 16.w),
        ),
      ],
    );
  }

  Widget _renderActivityItem(
    SpringActivityEntity activity,
    String imagePath,
    double aspectRatio,
  ) {
    return AspectRatio(
          aspectRatio: aspectRatio,
          child: Image.asset(
            imagePath,
            fit: BoxFit.fill,
            errorBuilder: (context, error, stackTrace) {
              return Container(
                decoration: BoxDecoration(
                  color: const Color(0xFF2AB061),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child:
                    Icon(
                      Icons.local_activity,
                      size: 50.sp,
                      color: Colors.white,
                    ).center(),
              );
            },
          ),
        )
        .parent(
          ({required Widget child}) => Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12.r),
            ),
            clipBehavior: Clip.hardEdge,
            child: child,
          ),
        )
        .inkWell(
          onTap: () {
            GoRouter.of(
              context,
            ).push('/activity-detail/${activity.activityId}');
          },
        )
        .padding(horizontal: 16.w);
  }
}
